<template>
  <div class='app-container'>
    <el-card class="box-card">

      <div slot="header" class="clearfix">
        <span>试题录入</span>
        何鹏江
      </div>
      <!-- 表单 -->
      <el-form ref="form" :model="newForm" :rules="rules" label-width="120px">
        <el-form-item label="学科:" prop="subjectID">
          <el-select placeholder="请选择" style="width: 400px;" @change='getSubjectSimple' v-model="newForm.subjectID" >
            <el-option
              v-for="item in subjectList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录:" prop="catalogID">
          <el-select placeholder="请选择" style="width: 400px;" v-model="newForm.catalogID" >
            <el-option
              v-for="item in subjectDetaillist"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业:" prop="enterpriseID">
          <el-select placeholder="请选择" style="width: 400px;" v-model="newForm.enterpriseID" >
            <el-option
              v-for="item in companysList"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市:" prop="city">
              <el-select
              v-model="newForm.province"
              @change="disposeAddress"
              placeholder="请选择"
              class="input_ib"
              style="margin-right: 4px; width: 198px;">
                <el-option
                  v-for="item in provinces"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
              <el-select v-model="newForm.city" placeholder="请选择" style="width: 198px;" class="input_ib">
                <el-option
                  v-for="item in citys"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
        <el-form-item label="方向:" prop="direction">
          <el-select placeholder="请选择" style="width: 400px;" v-model="newForm.direction" >
            <el-option label="o2o" value="o2o"></el-option>
            <el-option label="外包服务" value="外包服务"></el-option>
            <el-option label="企业服务" value="企业服务"></el-option>
            <el-option label="互联网金融" value="互联网金融"></el-option>
            <el-option label="企业咨询" value="企业咨询"></el-option>
            <el-option label="互联网" value="互联网"></el-option>
            <el-option label="电子商务" value="电子商务"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型:" prop="questionType">
          <el-radio-group v-model="newForm.questionType">
            <el-radio label="1" @change="radioChoice">单选</el-radio>
            <el-radio label="2" @change="multiChoice">多选</el-radio>
            <el-radio label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度:" prop="difficulty">
          <el-radio-group v-model="newForm.difficulty">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">一般</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干:" prop="question">
          <quill-editor
            ref=""
            v-model="newForm.question"
            :options='editorOption'
            @blur="onEditorBlur($event)"
            />
        </el-form-item>
        <el-form-item label="选项:" v-if="newForm.questionType !== '3'">
          <div class="avatar_options" v-for="(item,index) in newForm.options" :key="index">
            <el-radio v-if="newForm.questionType === '1'" v-model="isRight" :label="index" style="margin-right: 10px;">{{options[index]+':'}}</el-radio>
            <el-checkbox v-if="newForm.questionType === '2'" v-model="checkList" :label="index" style="margin-right: 10px;">{{options[index]+':'}}</el-checkbox>
            <el-input placeholder="请输入内容" v-model="item.title" style="width: 240px;"></el-input>
            <div class="avatar">
              <UploadImage v-model="item.img" />
            </div>
          </div>

          <!-- 新增按钮 -->
          <el-button type="danger" size="small" @click="optionAdd" :disabled="this.newForm.questionType === '1'">+增加选项与答案</el-button>
        </el-form-item>
        <el-form-item label="解析视频:">
          <el-input v-model="newForm.videoURL" style="width: 400px;"></el-input>
        </el-form-item>
        <el-form-item label="答案解析:" prop="answer">
          <quill-editor
            ref="quill"
            v-model="newForm.answer"
            :options='editorOption'
            @blur="onEditorBlur1($event)"
            />
        </el-form-item>
        <el-form-item label="题目备注:">
          <el-input type="textarea" v-model="newForm.remarks" style="width: 400px;"></el-input>
        </el-form-item>
        <el-form-item label="试题标签:">
          <el-select
            v-model="newForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择标签"
            style="width: 400px;min-height: 33px;">
            <el-option
              v-for="item in subjectTagsList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-if="!isID" @click="questionsAdd" >确认提交</el-button>
          <el-button type="success" v-if="isID" @click="questionsUpdate" >确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { provinces, citys } from '@/api/hmmm/citys.js'
import UploadImage from '@/components/UploadImage'
import { simple as subjectSimpe } from '@/api/hmmm/subjects.js'
import { simple as directorysSimpe } from '@/api/hmmm/directorys.js'
import { simple as creatorSimpe } from '@/api/base/users.js'
import { simple as tagsSimpe } from '@/api/hmmm/tags.js'
import { list as companysList } from '@/api/hmmm/companys.js'
import { add as questionAdd, detail as questionDetail, update as questionUpdate } from '@/api/hmmm/questions.js'

// import { add as questionsAdd } from '@/api/hmmm/questions.js'
export default {
  data () {
    return {
      newForm: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 企业城市
        city: '', // 所在城市下属地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [ // 选项
          // {
          //   code: '', // 代码
          //   title: '', // 标题
          //   img: '', // 图片URL
          //   isRight: '' // 是否为正确答案
          // }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标签
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'change' }],
        city: [{ required: true, message: '请选择地区', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'change' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'change' }],
        question: [{ required: true, message: '请输入题干', trigger: 'change' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'change' }]

      },

      citys: [], // 所在城市下属城市
      provinces: [], // 企业所属地域
      radio: true,
      subjectList: [], // 学科列表
      creatorList: [], // 录入人列表
      subjectDetaillist: [], // 二级目录列表
      subjectTagsList: [], // 标签列表
      companysList: [], // 企业列表

      optionLength: 4, // 有多少个选项
      options: [], // 选项(A,B,C)
      isRight: '', // 单选选中的索引
      checkList: [], // 复选 选中索引的集合
      radioChoiceList: [], // 点击多选时 保存单选的数据
      multiChoiceList: [], // 点击单选时 保存多选的数据
      multiOptionLength: '', // 点击单选时 保存多选的选项数

      isID: false, // 判断是否为修改

      editorOption: { // 工具栏
        placeholder: '请在这里输入',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            // [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            // [{ script: 'sub' }, { script: 'super' }], // 上下标
            // [{ indent: '-1' }, { indent: '+1' }], // 缩进
            // [{ direction: 'rtl' }], // 文本方向
            // [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
            // [{ header: [1, 2, 3, 4, 5, 6, false] }], // 几级标题
            // [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            // [{ font: [] }], // 字体
            // [{ align: [] }], // 对齐方式
            // ['clean'], // 清除字体样式
            ['image', 'video'] // 上传图片、上传视频
          ]
        },
        theme: 'snow'
      }
    }
  },

  watch: {
    '$route.query.id': {
      immediate: true,
      async handler (newVal, val) {
        if (newVal) {
          this.isID = true
          await this.loadQuestionDetail(this.$route.query.id)
          this.$nextTick(function () {
            this.$refs.quill.quill.enable(true)
            this.$refs.quill.quill.blur()
          })
        }
      }
    }
  },

  components: {
    UploadImage
  },

  computed: {

  },

  created () {
    this.provinces = provinces()
    this.loadSubjectSimple()
    this.loadCompanysList()
    this.loadCreatorSimpe()
    if (!this.newForm.options.length) {
      this.option()
    }
  },

  mounted () {
    this.$refs.quill.quill.enable(false)
  },

  methods: {
    // 富文本失去焦点
    onEditorBlur (e) {
      this.$refs.form.validateField('question')
    },

    onEditorBlur1 (e) {
      this.$refs.form.validateField('answer')
    },

    // questionsUpdate
    async questionsUpdate () {
      this.newForm.tags = this.newForm.tags.join(',') || ''
      this.choices()
      this.newForm.options.forEach((item, index) => {
        this.options.forEach((item1, index1) => {
          if (index === index1) {
            item.code = item1
          }
        })
      })
      if (this.newForm.questionType === '3') {
        this.newForm.options = []
      }
      await this.$refs.form.validate()
      await questionUpdate(this.newForm)
      this.$message.success('修改成功')
      if (this.newForm.isChoice) {
        this.$router.push('choice')
      } else {
        this.$router.push('list')
      }
    },

    // 获取修改数据
    async loadQuestionDetail (id) {
      id = Number(id)
      const res = await questionDetail({ id: id })
      console.log(res)
      this.onOptions(res.data)
      res.data.tags = res.data.tags.split(',')
      this.newForm = res.data
    },

    onOptions (row) {
      const options = []
      for (let i = 0; i < row.options.length; i++) {
        const str = 'A'
        const option = String.fromCharCode(str.charCodeAt() + i)
        const arr = row.options.filter((item, index) => {
          return item.code === option
        })
        options.push(arr[0])
      }
      options.forEach((item, index) => {
        if (row.questionType === '1' && item.isRight === 1) {
          this.isRight = index
        }
        if (row.questionType === '2' && item.isRight === 1) {
          this.checkList.push(index)
        }
      })
      row.options = options
    },

    //
    option () {
      this.options = []
      if (this.newForm.questionType === '1' && this.radioChoiceList.length !== 0) {
        for (let i = 0; i < 4; i++) {
          const str = 'A'
          this.options.push(String.fromCharCode(str.charCodeAt() + i))
        }
        this.newForm.options = this.radioChoiceList
        return
      }
      if (this.newForm.questionType === '2' && this.multiChoiceList.length !== 0) {
        for (let i = 0; i < this.optionLength; i++) {
          const str = 'A'
          this.options.push(String.fromCharCode(str.charCodeAt() + i))
        }
        this.newForm.options = this.multiChoiceList
        if (this.newForm.options.length < this.options.length) {
          this.newForm.options.push({ code: '', title: '', img: '', isRight: '' })
        }
        return
      }

      this.newForm.options = []
      for (let i = 0; i < this.optionLength; i++) {
        const str = 'A'
        this.options.push(String.fromCharCode(str.charCodeAt() + i))
        this.newForm.options.push({ code: '', title: '', img: '', isRight: '' })
      }
      console.log(this.options)
    },

    // onRadio
    onRadio (val) {
      console.log(val)
    },

    // 选择地域后触发
    disposeAddress (val) {
      console.log(val)
      this.citys = citys(val)
    },

    // 获取学科简单列表
    async loadSubjectSimple () {
      const res = await subjectSimpe()
      this.subjectList = res.data
      console.log(res.data)
    },

    // 获取录入人列表
    async loadCreatorSimpe () {
      const res = await creatorSimpe()
      this.creatorList = res.data
    },

    // 获取公司列表
    async loadCompanysList () {
      const res = await companysList({ pagesize: 10000 })
      console.log(res)
      this.companysList = res.data.items
    },

    // 获取二级目录 和 标签
    async getSubjectSimple () {
      const res = await directorysSimpe({ subjectID: this.newForm.subjectID })
      this.subjectDetaillist = res.data
      const res2 = await tagsSimpe({ subjectID: this.newForm.subjectID })
      this.subjectTagsList = res2.data
    },

    // 点击单选
    radioChoice () {
      this.multiChoiceList = this.newForm.options
      const arr = []
      for (let i = 0; i < 4; i++) {
        arr.push(this.newForm.options[i])
        this.radioChoiceList = arr
      }
      this.multiOptionLength = this.optionLength
      this.optionLength = 4
      this.option()
      this.choices()
    },

    // 点击多选
    multiChoice () {
      this.radioChoiceList = this.newForm.options
      if (this.multiChoiceList.length === 0) {
        this.multiChoiceList = this.newForm.options
      }
      if (this.multiChoiceList.length !== 0) {
        this.multiChoiceList[0] = this.radioChoiceList[0]
        this.multiChoiceList[1] = this.radioChoiceList[1]
        this.multiChoiceList[2] = this.radioChoiceList[2]
        this.multiChoiceList[3] = this.radioChoiceList[3]
      }
      console.log(this.multiOptionLength)
      this.optionLength = this.multiOptionLength || 4
      console.log(this.optionLength)
      this.option()
      this.choices()
    },

    // 选项
    choices () {
      if (this.newForm.questionType === '1') {
        this.newForm.options.forEach((item, index) => {
          item.isRight = false
          if (index === this.isRight) {
            item.isRight = true
          }
        })
      }
      if (this.newForm.questionType === '2') {
        this.newForm.options.forEach((item, index) => {
          item.isRight = false
          this.checkList.forEach(item1 => {
            if (index === item1) {
              item.isRight = true
            }
          })
        })
      }
    },

    // 增加选项
    optionAdd () {
      this.optionLength = this.optionLength + 1
      this.option()
    },

    // 添加试题
    async questionsAdd () {
      this.newForm.tags = this.newForm.tags.join(',') || ''
      this.choices()
      this.newForm.options.forEach((item, index) => {
        this.options.forEach((item1, index1) => {
          if (index === index1) {
            item.code = item1
          }
        })
      })
      console.log(this.newForm.tags)
      if (this.newForm.questionType === '3') {
        this.newForm.options = []
      }
      await this.$refs.form.validate()
      await questionAdd(this.newForm)
      this.$message.success('新增试题成功')
      this.$router.push('list')
    }

  }
}
</script>

<style scoped lang='less'>
/deep/.ql-editor {
    height: 200px;
}
/deep/.avatar_options {
  line-height: 60px;
  padding-bottom: 20px;
  .avatar {
    display: inline-block;
    position: relative;
    width: 100px;
    height: 60px;
    margin-left: 5px;

    .el-upload--picture-card {
      position: relative;
      width: 100px;
      height: 60px;

      span {
        position: absolute;
        top: -80%;
        left: 20%;
        // transform: translate(-50%,-50%);
      }
    }

    .el-progress {
      position: absolute;
      top: 40%;
      width: 60px;
      height: 60px;

      .el-progress-circle {
        width: 100%!important;
        height: 100%!important;
      }
    }

    .el-upload-list__item {
      width: 100px;
      height: 60px;
    }

    .display {
      width: 100px;
      height: 60px;
    }
  }
}
</style>
